package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    private final String addr = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    /**
     * C端用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //获取用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        log.info("已获取到当前用户openid:{}",openid);
        //判断是否获取成功
        if(openid==null){
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }
        //用户已登录  判断当前用户是否是新用户
        User user=userMapper.getUserByOpenid(openid);
        if(user==null){
            //新用户  注册
             user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);
            return user;
        }else {
            //不是新用户  直接返回
            return user;
        }
    }

    /**
     * 获取用户的openid
     */
    public String getOpenid(String code){
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json_object = HttpClientUtil.doGet(addr, map);
        JSONObject object = JSON.parseObject(json_object);
        return object.getString("openid");
    }
}
